package com.raptor.trustworthycore.util;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Vector;
import org.apache.log4j.Logger;

/**
 * 使用SFTP协议上传下载文件工具类
 * @author renhuan
 */
public class SftpUtil {

    private static Logger logger = Logger.getLogger(SftpUtil.class);

    /**
     * 服务器地址
     */
    private String host;
    /**
     * 用户名
     */
    private String username;
    /**
     * 密码
     */
    private String password;
    /**
     * 端口
     */
    private int port;

    private ChannelSftp sftp = null;

    private final static int TIME_OUT = 60000;
    /**
     * 编码格式
     */
    private static String coding = "UTF-8";

    /**
     * 基本参数构造
     * @param host 服务器地址
     * @param port 服务器端口
     * @param username 用户名
     * @param password 密码
     */
    public SftpUtil(String host,int port,String username,String password){
        this.host = host;
        this.port = port;
        this.username = username;
        this.password = password;
    }


    /**
     * 连接sftp服务器
     */
    public String connect() {
        String eStr = "";
        try {
            JSch jsch = new JSch();
            jsch.getSession(username, host, port);
            //根据用户名，主机ip，端口获取一个Session对象
            Session sshSession = jsch.getSession(username, host, port);
            //设置密码
            sshSession.setPassword(password);
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            //为Session对象设置properties
            sshSession.setConfig(sshConfig);
            sshSession.setTimeout(TIME_OUT);
            sshSession.connect();
            Channel channel = sshSession.openChannel("sftp");
            channel.connect();
            sftp = (ChannelSftp) channel;
            //sftp.setFilenameEncoding(coding);
            return "true";
        } catch (Exception e) {
            logger.error("SFTP connect exception :",e);
            eStr = "SFTP connect exception :" + e.toString();
        }
        return eStr;
    }
    /**
     * Disconnect with server
     */
    public void disconnect() {
        if(this.sftp != null){
            if(this.sftp.isConnected()){
                this.sftp.disconnect();
            }
        }
    }



    /**
     * 上传文件
     * @param remotePath 远程文件路径(包括完整路径)
     * @param localPath 本地文件名(包括完整路径)
     * @return
     */
    public String upload(String remotePath,String localPath) {
        String eStr = "true";
        FileInputStream input = null;
        try {
            File file = new File(localPath);
            if(file.isFile()){
                createDir(remotePath);
                input = new FileInputStream(file);
                this.sftp.put(input, new String(file.getName().getBytes(coding), coding));
            }
        } catch (FileNotFoundException e) {
            logger.error(getExceptionString(e));
            eStr = getExceptionString(e);
        } catch (SftpException e) {
            logger.error(getExceptionString(e));
            eStr = getExceptionString(e);
        } catch (Exception e) {
            logger.error(getExceptionString(e));
            eStr = getExceptionString(e);
        } finally {
            if (input != null){
                try {
                    input.close();
                } catch (IOException e) {
                    logger.error(getExceptionString(e));
                }
            }
        }
        return eStr;
    }

    /**
     * 删除文件
     *
     * @param directory  要删除文件所在目录
     * @param deleteFile 要删除的文件
     * @throws Exception
     */
    public void deleteFile(String directory, String deleteFile) {
        try {
            this.sftp.cd(directory);
            this.sftp.rm(deleteFile);
        } catch (Exception e) {
            logger.error(getExceptionString(e));
        }
    }

    /**
     * 下载文件
     * @param directory
     * @param downloadFile
     * @param saveFile
     * @return
     */
    public boolean download(String directory, String downloadFile,String saveFile) {
        FileOutputStream fos = null;
        try {
            this.sftp.cd(directory);
            File file = new File(saveFile);
            fos = new FileOutputStream(file);
            this.sftp.get(downloadFile, fos);
            return true;
        } catch (Exception e) {
            logger.error(getExceptionString(e));
        } finally {
            try {
                if (fos!=null) {
                    fos.close();
                }
            } catch (IOException e) {
                logger.error(getExceptionString(e));
            }
        }
        return false;
    }

    /**
     * 创建一个文件目录
     */
    public void createDir(String createpath) {
        try{
            if(isDirExist(createpath)) {
                this.sftp.cd(createpath);
                return;
            }
            String pathArry[] = createpath.split("/");
            StringBuffer filePath = new StringBuffer("/");
            for(String path : pathArry) {
                if(path==null && "".equals(path)) {
                    continue;
                }
                filePath.append(path + "/");
                if(isDirExist(filePath.toString())) {
                    this.sftp.cd(filePath.toString());
                }else {
                    // 建立目录
                    this.sftp.mkdir(filePath.toString());
                    // 进入并设置为当前目录
                    this.sftp.cd(filePath.toString());
                }
            }
            this.sftp.cd(createpath);
        } catch (SftpException e) {
            logger.error(getExceptionString(e));
        }
    }

    /**
     * 判断目录是否存在
     */
    public boolean isDirExist(String directory) {
        boolean isDirExistFlag = false;
        try{
            SftpATTRS sftpATTRS = sftp.lstat(directory);
            isDirExistFlag = true;
            return sftpATTRS.isDir();
        }catch (Exception e) {
            if(e.getMessage().toLowerCase().contains("no such file")) {
                isDirExistFlag = false;
            }
        }
        return isDirExistFlag;
    }

    /**
     * 列出目录下的文件
     *
     * @param directory 要列出的目录
     * @param regex  指定文件名的格式
     * @return 文件名列表
     * @throws SftpException
     *             SftpException
     * @throws
     *             SPMException
     */
    public List<String> listFiles(String directory, String regex) {
        List<String> ftpFileNameList = new ArrayList<String>();
        try {
            Vector<LsEntry> sftpFile = sftp.ls(directory);
            LsEntry isEntity = null;
            String fileName = null;
            Iterator<LsEntry> sftpFileNames = sftpFile.iterator();
            while(sftpFileNames.hasNext()) {
                isEntity = (LsEntry) sftpFileNames.next();
                fileName = isEntity.getFilename();
                if(".".equals(fileName) || "..".equals(fileName)){
                    continue;
                }
                if(regex==null || "".equals(regex)) {
                    ftpFileNameList.add(fileName);
                }else if(fileName.contains(regex)) {
                    ftpFileNameList.add(fileName);
                }
            }
        } catch (SftpException e) {
            e.printStackTrace();
        }
        return ftpFileNameList;
    }

    /**
     * 获取异常信息内容
     * @param e 异常对象
     * @return 返回异常信息内容
     */
    public static String getExceptionString(Exception e) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(os);
        e.printStackTrace(ps);
        String msg = os.toString();
        return msg;
    }

}  